% Calculates GradInd
%
% GradInd is a vector of indexes. It is used when applying the stochastic
% dicount factor in the "taking expectations" operation in the value
% function iteration. Since ProbNgr moves nominal aggregate demand to a
% (usually) higher level we much multiply by inflation to be able to
% compare tomorrow's real aggregate demand with today's real aggregate
% demand in applying the stochastic discount factor. This is what GradInd
% does.
%
% Jon Steinsson and Emi Nakamura, July 2006 (modified Sept 2015)
%**********************************************************************

function GradInd = CalculateGradInd(rad,G)

radgridsize = size(rad,1);
Ssize = radgridsize^2;

rad2Value = repmat(rad',[radgridsize 1]);
rad2Value = reshape(rad2Value,[Ssize 1]);

G = repmat(G, [1 radgridsize]);
G = reshape(G,[Ssize 1]);

rad2Value = rad2Value - G;

rad2Value = (rad2Value < min(rad)*ones(Ssize,1)).*(min(rad)*ones(Ssize,1)) ...
    + (rad2Value > max(rad)*ones(Ssize,1)).*(max(rad)*ones(Ssize,1)) ...
    + (rad2Value >= min(rad)*ones(Ssize,1) & rad2Value <= max(rad)*ones(Ssize,1)).*rad2Value;

radInd = repmat((1:radgridsize)',[1 radgridsize]);
radInd = reshape(radInd,[Ssize 1]);

[dummy,rad2Ind] = ismember(int32(rad2Value*10^8),int32(rad*10^8));
clear dummy
clear rad2Value

GradInd = sub2ind([radgridsize radgridsize],radInd,rad2Ind);

